import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../api/api_service.dart';
import '../../models/post.dart';
import '../../utils/app_icons.dart';
import '../../config/app_theme.dart';
import '../../providers/app_state.dart';
import 'post_detail_screen.dart';
import 'publish_post_screen.dart';

class CommunityScreen extends StatefulWidget {
  @override
  _CommunityScreenState createState() => _CommunityScreenState();
}

class _CommunityScreenState extends State<CommunityScreen> with SingleTickerProviderStateMixin {
  final ApiService _apiService = ApiService();
  late TabController _tabController;
  List<Post> _recommendedPosts = [];
  List<Post> _latestPosts = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _loadPosts();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadPosts() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final recommendedPosts = await _apiService.getPosts(
        limit: 20,
        offset: 0,
        sortBy: 'popular',
      );
      
      final latestPosts = await _apiService.getPosts(
        limit: 20,
        offset: 0,
        sortBy: 'latest',
      );

      setState(() {
        _recommendedPosts = recommendedPosts;
        _latestPosts = latestPosts;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error loading posts: $e');
    }
  }

  void _navigateToPostDetail(Post post) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PostDetailScreen(post: post),
      ),
    );
  }

  void _navigateToPublishPost() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('发布新帖子'),
          content: Text('即将添加发布新帖子功能，敬请期待！'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('关闭'),
            ),
          ],
        );
      },
    );
    
    // 实际功能可以使用以下代码
    // Navigator.push(
    //   context,
    //   MaterialPageRoute(
    //     builder: (context) => PublishPostScreen(),
    //   ),
    // );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('宠友社区'),
        actions: [
          IconButton(
            icon: Image.asset(AppIcons.search, width: 24, height: 24, color: Colors.white),
            onPressed: () {
              // TODO: 实现搜索功能
            },
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: Colors.white,
          tabs: [
            Tab(text: '推荐'),
            Tab(text: '最新'),
          ],
        ),
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : TabBarView(
              controller: _tabController,
              children: [
                _buildPostList(_recommendedPosts),
                _buildPostList(_latestPosts),
              ],
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: _navigateToPublishPost,
        backgroundColor: AppTheme.primaryColor,
        child: Image.asset(AppIcons.add, width: 24, height: 24, color: Colors.white),
      ),
    );
  }

  Widget _buildPostList(List<Post> posts) {
    if (posts.isEmpty) {
      return Center(
        child: Text('暂无帖子'),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadPosts,
      child: ListView.builder(
        padding: EdgeInsets.all(16.0),
        itemCount: posts.length,
        itemBuilder: (context, index) {
          final post = posts[index];
          return _buildPostCard(post);
        },
      ),
    );
  }

  Widget _buildPostCard(Post post) {
    final appState = Provider.of<AppState>(context);
    final bool isFavorite = appState.favoritePosts.contains(post.id);
    
    return GestureDetector(
      onTap: () => _navigateToPostDetail(post),
      child: Container(
        margin: EdgeInsets.only(bottom: 16.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 帖子头部：用户信息
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: Row(
                children: [
                  CircleAvatar(
                    radius: 20,
                    backgroundImage: NetworkImage(post.userAvatar),
                  ),
                  SizedBox(width: 12.0),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          post.userName,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16.0,
                          ),
                        ),
                        SizedBox(height: 2.0),
                        Text(
                          _formatDate(post.createdAt),
                          style: TextStyle(
                            color: Colors.grey,
                            fontSize: 12.0,
                          ),
                        ),
                      ],
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.more_horiz),
                    onPressed: () {
                      // TODO: 显示更多选项菜单
                    },
                  ),
                ],
              ),
            ),
            
            // 帖子内容
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    post.title,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18.0,
                    ),
                  ),
                  SizedBox(height: 8.0),
                  Text(
                    post.content,
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 14.0),
                  ),
                ],
              ),
            ),
            
            // 帖子图片
            if (post.images.isNotEmpty)
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: _buildPostImages(post),
              ),
            
            // 帖子底部操作栏
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildActionButton(
                    icon: Icons.thumb_up_outlined,
                    count: post.likes,
                    onPressed: () {
                      // TODO: 点赞功能
                    },
                  ),
                  _buildActionButton(
                    icon: Icons.comment_outlined,
                    count: post.comments,
                    onPressed: () => _navigateToPostDetail(post),
                  ),
                  _buildActionButton(
                    icon: isFavorite ? Icons.favorite : Icons.favorite_border,
                    count: post.favorites,
                    isActive: isFavorite,
                    onPressed: () {
                      appState.toggleFavoritePost(post.id);
                    },
                  ),
                  _buildActionButton(
                    icon: Icons.share_outlined,
                    label: '分享',
                    onPressed: () {
                      // TODO: 分享功能
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPostImages(Post post) {
    if (post.images.length == 1) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(8.0),
        child: Image.network(
          post.images.first,
          height: 200,
          width: double.infinity,
          fit: BoxFit.cover,
        ),
      );
    } else {
      return GridView.count(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: post.images.length >= 3 ? 3 : 2,
        mainAxisSpacing: 8.0,
        crossAxisSpacing: 8.0,
        children: post.images.take(6).map((imageUrl) {
          return ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: Image.network(
              imageUrl,
              fit: BoxFit.cover,
            ),
          );
        }).toList(),
      );
    }
  }

  Widget _buildActionButton({
    required IconData icon,
    int? count,
    String? label,
    bool isActive = false,
    required VoidCallback onPressed,
  }) {
    return InkWell(
      onTap: onPressed,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 8.0),
        child: Row(
          children: [
            Icon(
              icon,
              size: 20.0,
              color: isActive ? Colors.red : Colors.grey,
            ),
            SizedBox(width: 4.0),
            Text(
              label ?? (count?.toString() ?? '0'),
              style: TextStyle(
                color: isActive ? Colors.red : Colors.grey,
                fontSize: 12.0,
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.month}月${date.day}日';
  }
} 